package org.ruoyi.common.dhuman.ppt;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.sl.usermodel.*;
import org.ruoyi.common.core.utils.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

public class PPTProcessor {

	/**
	 * 处理PPT文件（支持.ppt和.pptx格式）
	 */
	public PPTContent processPPT(String filePath, String ocrLanguagePath) {
		PPTContent content = new PPTContent();

		try {
			if (filePath.toLowerCase().endsWith(".pptx")) {
				processPPTX(filePath, content, ocrLanguagePath);
			} else if (filePath.toLowerCase().endsWith(".ppt")) {
				processPPT(filePath, content, ocrLanguagePath);
			} else {
				throw new IllegalArgumentException("Unsupported file format. Only .ppt and .pptx are supported.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return content;
	}

	/**
	 * 处理.pptx格式文件
	 */
	private void processPPTX(String filePath, PPTContent content, String ocrLanguagePath) throws Exception {
		try (FileInputStream fis = new FileInputStream(filePath)) {
			XMLSlideShow ppt = new XMLSlideShow(fis);

			// 获取所有幻灯片
			List<XSLFSlide> slides = ppt.getSlides();
			content.setTotalSlides(slides.size());

			for (int i = 0; i < slides.size(); i++) {
				SlideContent slideContent = new SlideContent(i + 1);
				XSLFSlide slide = slides.get(i);

				// 提取文字内容
				extractTextFromSlide(slide, slideContent);

				// 提取并处理图片
				extractAndProcessImages(slide, slideContent, ocrLanguagePath);

				content.addSlide(slideContent);
			}

			ppt.close();
		}
	}

	/**
	 * 处理.ppt格式文件
	 */
	private void processPPT(String filePath, PPTContent content, String ocrLanguagePath) throws Exception {
		try (FileInputStream fis = new FileInputStream(filePath)) {
			HSLFSlideShow ppt = new HSLFSlideShow(fis);

			// 获取所有幻灯片
			List<HSLFSlide> slides = ppt.getSlides();
			content.setTotalSlides(slides.size());

			for (int i = 0; i < slides.size(); i++) {
				SlideContent slideContent = new SlideContent(i + 1);
				HSLFSlide slide = slides.get(i);

				// 提取文字内容
				extractTextFromSlide(slide, slideContent);

				// 提取并处理图片
				extractAndProcessImages(slide, slideContent, ocrLanguagePath);

				content.addSlide(slideContent);
			}

			ppt.close();
		}
	}

	/**
	 * 从幻灯片提取文字
	 */
	private void extractTextFromSlide(Slide slide, SlideContent slideContent) {
		StringBuilder textBuilder = new StringBuilder();

		for (Object shape : slide.getShapes()) {
			if (shape instanceof TextShape) {
				TextShape textShape = (TextShape) shape;
				String text = textShape.getText();
				if (text != null && !text.trim().isEmpty()) {
					textBuilder.append(text).append("\n");
				}
			}
		}

		slideContent.setTextContent(textBuilder.toString().trim());
	}

	/**
	 * 提取并处理图片
	 */
	private void extractAndProcessImages(Slide slide, SlideContent slideContent, String ocrLanguagePath) {
		try {
			for (Object shape : slide.getShapes()) {
				if (shape instanceof PictureShape) {
					PictureShape picture = (PictureShape) shape;
					PictureData pictureData = picture.getPictureData();

					// 将图片数据转换为BufferedImage
					byte[] imageData = pictureData.getData();
					ByteArrayInputStream bis = new ByteArrayInputStream(imageData);
					BufferedImage image = ImageIO.read(bis);

					if (image != null) {
						ImageContent imageContent = new ImageContent();
						imageContent.setImageData(imageData);
						imageContent.setFormat(pictureData.getType().extension);

						// 识别图片中的文字
						String ocrText = performOCR(image, ocrLanguagePath);
						imageContent.setOcrText(ocrText);

						slideContent.addImage(imageContent);
					}

					bis.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用Tesseract OCR识别图片文字
	 */
	private String performOCR(BufferedImage image, String ocrLanguagePath) {
		if (StringUtils.isEmpty(ocrLanguagePath)) {
			return StringUtils.EMPTY;
		}
		try {
			// 初始化Tesseract
			net.sourceforge.tess4j.Tesseract tesseract = new net.sourceforge.tess4j.Tesseract();

			// 设置语言包路径（需要提前下载中文语言包）
			tesseract.setDatapath(ocrLanguagePath);

			// 设置语言（英文+中文）
			tesseract.setLanguage("eng+chi_sim");

			// 设置OCR引擎模式
			tesseract.setOcrEngineMode(1);

			// 进行OCR识别
			return tesseract.doOCR(image);

		} catch (Exception e) {
			System.err.println("OCR识别失败: " + e.getMessage());
			return "OCR识别失败";
		}
	}
}